/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package cn.knet.sp.ncrm.modules.customer.potentialgroup.entity;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonFormat;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.Length;

import java.util.Date;

import javax.validation.constraints.NotNull;

import cn.knet.sp.ncrm.common.persistence.TreeEntity;
import cn.knet.sp.ncrm.modules.sys.user.entity.User;
import cn.knet.sp.ncrm.modules.sys.utils.UserUtils;

/**
 * 分组Entity
 *
 * @author 冯亚鹏
 * @version 2015-08-24
 */
public class PotentialGroup extends TreeEntity<PotentialGroup> {

	private static final long serialVersionUID = 1L;
	private Long version;        // version
	private Date dateCreated;        // 创建时间
	private Date lastUpdated;        // 最后更新时间
	private Integer levelNum;        // 等级level
	private String name;        // 分组名称
	private PotentialGroup parent;        // 父主键
	private User user;        // 用户id

	public PotentialGroup() {
		super();
	}

	public PotentialGroup(String id) {
		super(id);
	}

	public Long getVersion() {
		return version;
	}

	public void setVersion(Long version) {
		this.version = version;
	}

	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
	public Date getDateCreated() {
		return dateCreated;
	}

	public void setDateCreated(Date dateCreated) {
		this.dateCreated = dateCreated;
	}

	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
	public Date getLastUpdated() {
		return lastUpdated;
	}

	public void setLastUpdated(Date lastUpdated) {
		this.lastUpdated = lastUpdated;
	}

	public Integer getLevelNum() {
		return levelNum;
	}

	public void setLevelNum(Integer levelNum) {
		this.levelNum = levelNum;
	}

	@Length(min = 1, max = 64, message = "分组名称长度必须介于 1 和 64 之间")
	@NotNull(message = "分组不能为空")
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@JsonBackReference
	public PotentialGroup getParent() {
		return parent;
	}

	public void setParent(PotentialGroup parent) {
		this.parent = parent;
	}

	@JsonBackReference
	public User getUser() {
		return this.user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getParentId() {
		return parent != null && parent.getId() != null ? parent.getId() : "0";
	}


	@Override
	public void preUpdate() {
		super.preUpdate();
		this.version++;

		this.lastUpdated = new Date();
	}

	@Override
	public void preInsert() {
		super.preInsert();
		this.version = 0L;
		this.dateCreated = new Date();
		this.lastUpdated = new Date();
		User user = UserUtils.getUser();
		if (StringUtils.isNotBlank(user.getId())) {
			this.user = user;
		}
	}
}